package com.dameng.system.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static String path = System.getProperty("user.dir") + "/upload/";

    @GetMapping("/manager")
    public String manager() {
        return "file/manager";
    }

    @PostMapping("/upload")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file) throws IOException {
        Map<String, Object> map = new HashMap<>();
        boolean result = true;
        if (ObjectUtils.isEmpty(file)) {
            result = false;
        } else {
            String filename = file.getOriginalFilename();
            String suffixName = filename.substring(filename.lastIndexOf("."));
            filename = UUID.randomUUID().toString().replaceAll("-","") + suffixName;

            logger.debug("fileName:" + file.getOriginalFilename());
            logger.debug("contentType:" + file.getContentType());
            logger.debug("fileSize:" + file.getSize());
            logger.debug("saveFileName:" + filename);

            file.transferTo(new File(path + filename));
            map.put("fileId", filename);
        }
        map.put("result", result);
        return map;
    }

    @PostMapping("/delete")
    @ResponseBody
    public Object delete(String fileId) {
        File file = new File(path + fileId);
        if(file.isFile()){
            file.delete();
        }
        return true;
    }
}
